﻿using FileEfCore.DbContexts;
using FileServer.Core;
using FileServer.Core.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.Extensions.Hosting;

public static class HostBuilderExtensions
{
    public static IHostBuilder ConfigureFileSeverHostDefaults(this IHostBuilder builder)
    {
        builder
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureServices((hostBuilder, sc) =>
            {
                sc.AddFileServerServices(hostBuilder.Configuration, hostBuilder.HostingEnvironment);

                var dbType = hostBuilder.Configuration.GetSection("FileServerSetting:DbType").Get<DBType>();
                switch (dbType)
                {
                    case DBType.SqlLite:
                        AddSqlLiteDbContext(sc);
                        break;
                    case DBType.SqlServer:
                        AddSqlServerDbContext(sc,hostBuilder.Configuration);
                        break;
                    default:
                        throw new Exception($"暂不支持{dbType}的数据配置");
                }
                
                

                App.ServiceProvider = sc.BuildServiceProvider();
            });
        return builder;
    }

    private static void AddSqlServerDbContext(IServiceCollection sc, IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("default");
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new Exception("请先配置数据库链接");
        }
        sc.AddDbContext<ServerFileDbContext>(option =>
        {
            option.UseSqlServer(connectionString);
            option.UseLoggerFactory(new NullLoggerFactory());
        }, ServiceLifetime.Transient);
    }

    private static void AddSqlLiteDbContext(IServiceCollection sc)
    {
        var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        var dbPath = Path.Combine(homeDir, ".ums-file-server/fileinfo.db");
        CreateUmsDirectoryIfNotExist(Path.GetDirectoryName(dbPath));
        var connectionString = $"Data Source={dbPath}";
        sc.AddDbContext<ServerFileDbContext>(option =>
        {
            option.UseSqlite(connectionString);
            option.UseLoggerFactory(new NullLoggerFactory());
        }, ServiceLifetime.Transient);
    }

    private static void CreateUmsDirectoryIfNotExist(string directoryName)
    {
        if (!Directory.Exists(directoryName))
        {
            Directory.CreateDirectory(directoryName);
        }
    }
}